import { defineStore } from "pinia";
import { RoutesState } from "../interface";
import constantRoutes from "@/routers/modules/dynamicRouter";
import router from "@/routers";
const hasPermission = (authoritiesCode: string[], route: Menu.MenuOptions) => {
  if (route.meta && route.meta.permission) {
    const permission = route.meta.permission as [];
    return permission.some(v => authoritiesCode.includes(v));
  }
  return true;
};

export const filterAsyncRoutes = (routes: Array<Menu.MenuOptions>, authoritiesCode: string[]) => {
  const res: Array<Menu.MenuOptions> = [];
  routes.forEach(route => {
    const tmp = { ...route };
    if (hasPermission(authoritiesCode, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, authoritiesCode);
      } else {
        res.push(tmp);
      }
      if (tmp.children && tmp.children.length > 0) {
        tmp.redirect = tmp.children[0].path;
        res.push(tmp);
      }
    }
  });
  return res;
};
const useRoutesStore = defineStore({
  id: "routesStore",
  state: (): RoutesState => ({
    dynamicsRoutes: [] as Array<Menu.MenuOptions>
  }),
  actions: {
    setDynameicsRoutes(routes: Array<Menu.MenuOptions>) {
      this.dynamicsRoutes = routes;
    },
    generateDynameicsRoutes(authoritiesCode: string[]) {
      return new Promise<Array<Menu.MenuOptions>>(resolve => {
        const accessedRoutes: Array<Menu.MenuOptions> = filterAsyncRoutes(constantRoutes, authoritiesCode);
        this.setDynameicsRoutes(accessedRoutes);
        this.setRouter();
        resolve(accessedRoutes);
      });
    },
    setRouter() {
      //设置动态路由到 路由中
      this.dynamicsRoutes.forEach((item: any) => {
        router.addRoute(item);
      });
    }
  }
});

export default useRoutesStore;
